package com.zl.learning.json.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider;
import com.alibaba.fastjson.parser.deserializer.PropertyProcessable;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Test1 {

    class MyExtra implements ExtraProcessor, ExtraTypeProvider {
        int index = 0;

        @Override
        public void processExtra(Object object, String key, Object value) {
            if (object instanceof CollisionResult) {
                if (key.equals("collisionresult")) {
                    List<CollisionResult> collisionResults = (List<CollisionResult>) value;
                    object = collisionResults.get(index);
                    index++;
                }
            }

        }

        @Override
        public Type getExtraType(Object object, String key) {
            if (key.equals("collisionresult")) {
                return new TypeReference<List<CollisionResult>>() {
                }.getType();
            }
            return null;
        }
    }

    @Test
    public void test1() throws IOException {
        JSONObject object = JSON.parseObject(Files.newInputStream(Paths.get("1.json")), JSONObject.class);
        System.out.println(object.getJSONArray("collisionresult").toJavaList(CollisionResult.class));
    }

    @Test
    public void test2() throws IOException {
        PropertyProcessable processable = new PropertyProcessable() {

            @Override
            public Type getType(String name) {

                return null;
            }

            @Override
            public void apply(String name, Object value) {
                System.out.println(value);
            }
        };
        String jsonStr = new String(Files.readAllBytes(Paths.get("1.json")));
        Result<List<CollisionResult>> result = JSON.parseObject(jsonStr, new TypeReference<Result<List<CollisionResult>>>() {
        }.getType(), new MyExtra());
        System.out.println(result);
    }

    @Test
    public void test3() throws IOException {
        Result<List<CollisionResult>> collisionResults = getResult();
        System.out.println(collisionResults);
    }

    private Result<List<CollisionResult>> getResult() throws IOException {
        String jsonStr = new String(Files.readAllBytes(Paths.get("1.json")));
        Result result = JSON.parseObject(jsonStr, Result.class);
        List<CollisionResult> collisionResults = JSON.parseObject(JSON.toJSONString(result.getData())).getJSONArray("collisionresult").toJavaList(CollisionResult.class);
        result.setData(collisionResults);
        return result;
    }
}
